package com.itheima;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class CuratorTest01 {
    /*
    建立连接
     */
    private   CuratorFramework client;
    @Before
    public void testConnect(){
//        第一种方式
        /* 参数: 地址和端口
                会话超时时间
                 连接超时时间
                 重试策略
                */
        RetryPolicy retryPolicy= new ExponentialBackoffRetry(3000,10);
//      CuratorFramework client= CuratorFrameworkFactory.newClient("192.168.23.129:2181",60*1000,15*1000,retryPolicy);
//      client.start();
//        第二种方式
        client= CuratorFrameworkFactory.builder()
               .connectString("192.168.23.129:2181")
               .sessionTimeoutMs(60*1000)
               .connectionTimeoutMs(15*10000)
               .retryPolicy(retryPolicy)
               .namespace("itheima")
               .build();
    }
    @After
    public void  testClose(){
        if (client!=null){
            client.close();
        }

    }
    /**
     * 演示 NodeCache：给指定一个节点注册监听器
     */
    @Test
    public void  testNodeCache() throws Exception {
        client.start();
        //1. 创建NodeCache对象
        final NodeCache nodeCache = new NodeCache(client,"/app1");
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点变化了~");
                //获取修改节点后的数据
                byte[] data = nodeCache.getCurrentData().getData();
                System.out.println(new String(data));
            }
        });
        //3. 开启监听.如果设置为true，则开启监听是，加载缓冲数据
        nodeCache.start(true);

        while (true){}



    }



}
